# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from CommonLib.mylog import mylog
from CommonLib.db.MongoDBTool import MongoDBTool
from CommonLib.FileTool.CsvTool import CsvTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
	指定日期区间的sina等数据insert，与ws同库
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class SinaDaySend:
	# init what
	def __init__(self):
		self.mongo = MongoDBTool()
		self.csvtool = CsvTool()
		self.db_name = supeanut_config.MONGO_DB
		self.coll_daydata = supeanut_config.MONGO_COLL_DAYDATA
		self.sina_path = supeanut_config.SINA_DAYDATA_CSV_PATH
	

	# 插入(更新)指定日期的数据, 
	def upsert_date(self, date_list):
		flag, msg = self.mongo.conn(self.db_name, self.coll_daydata)
		if flag is False:
			return False, msg
		log = mylog('WsHistDaySend.insert_date', None)
		for filename in date_list:
			print filename
			flag,records = self.csvtool.read_csv(self.sina_path, filename)
			if flag is False:
				return False, 'read file %s failed'%filename
			for record in records:
				date = record[1]
				if date in date_list:
					doc = {}
					code = record[0].decode('utf-8')
					date = record[1].decode('utf-8')
					doc[u'open'] = record[2].decode('utf-8')
					if doc[u'open'] == u'0.000':
						continue
					doc[u'high'] = record[3].decode('utf-8')
					doc[u'low'] = record[4].decode('utf-8')
					doc[u'close'] = record[5].decode('utf-8')
					doc[u'vol_stock'] = record[6].decode('utf-8')
					doc[u'vol_capital'] = record[7].decode('utf-8')
					doc[u'datetime'] = date + u' 00:00:00'
					update_suc = False
					while not update_suc:
						try:
							self.mongo.coll.update_one({u'code':code, u'date':date},\
													{'$set':doc}, upsert = True)
						except:
							flag, msg = self.mongo.conn(self.db_name, self.coll_daydata)
							if flag is False:
								return False, traceback.format_exc()
							else:
								continue
						update_suc = True
		return True, 'suc'

if __name__ == '__main__':
	obj = SinaDaySend()
	obj.upsert_date(['2017-06-09'])
